package com.cl.filter;

import com.cl.pojo.User;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
@WebFilter(filterName = "UserFilter", urlPatterns = "*.html", dispatcherTypes = {})
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        String requestURI = req.getRequestURI();
        int i = requestURI.lastIndexOf("/");
        String endWith = requestURI.substring(i + 1);
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user==null){
            if (endWith.equals("admin.html")||endWith.equals("inlibrary.html")||endWith.equals("noticemanage.html")||endWith.equals("noticerelease.html")||endWith.equals("outlibrary.html")||endWith.equals("situation.html")||endWith.equals("statistics.html")||endWith.equals("stock.html")||endWith.equals("subscribe.html")||endWith.equals("today.html")||endWith.equals("vaccines.html")) {
                resp.sendRedirect("index.html");
            }else {
                chain.doFilter(req, resp);
            }
        }else{
            if (user.getuRole().equals("用户")){
                if (endWith.equals("admin.html")||endWith.equals("inlibrary.html")||endWith.equals("noticemanage.html")||endWith.equals("noticerelease.html")||endWith.equals("outlibrary.html")||endWith.equals("situation.html")||endWith.equals("statistics.html")||endWith.equals("stock.html")||endWith.equals("today.html")||endWith.equals("vaccines.html")){
                    resp.sendRedirect("index.html");
                }else {
                    chain.doFilter(req, resp);
                }
            }else if (user.getuRole().equals("管理员")){
                if (endWith.equals("subscribe.html")){
                    resp.sendRedirect("index.html");
                }else {
                    chain.doFilter(req, resp);
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}
